/**
 * 版权所有(C)，上海勾芒信息科技，2016，所有权利保留。
 * 
 * 项目名：	carwx
 * 文件名：	WxServiceUtil.java
 * 模块说明：	
 * 修改历史：
 * 2016年11月17日 - Debenson - 创建。
 */
package com.alex.wechat.mp.util;

import org.hibernate.service.spi.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alex.wechat.mp.account.entity.WxAccountEntity;
import com.alex.wechat.mp.account.service.WxAccountServiceI;
import com.gomore.jeecg.common.Assert;

import me.chanjar.weixin.mp.api.WxMpInMemoryConfigStorage;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.api.impl.WxMpServiceImpl;

/**
 * @author Debenson
 * @since 0.1
 */
@Component
public class WxServiceUtil {

  @Autowired
  private WxAccountServiceI accountService;

  /**
   * 取指定公众号的服务对象。
   * 
   * @param accountId
   *          公众号标识，禁止为null。
   * @return
   * @throws ServiceException
   *           如果找不到指定公众号抛出此异常。
   */
  public WxMpService getWxMpService(String accountId) throws ServiceException {
    Assert.assertArgumentNotEmpty(accountId, "accountId");

    final WxAccountEntity account = accountService.findUniqueByProperty(WxAccountEntity.class,
        "accountid", accountId);
    if (account == null) {
      throw new ServiceException("公众号不存在");
    }

    WxMpInMemoryConfigStorage config = new WxMpInMemoryConfigStorage();
    config.setAppId(account.getAppid());
    config.setSecret(account.getAppsecret());
    config.setToken(account.getToken());
    config.setAesKey(account.getAesKey());
    config.setAccessToken(account.getAccesstoken());
    config.setExpiresTime(account.getExpiresTime());
    config.setJsapiTicket(account.getJsapiticket());
    config.setJsapiTicketExpiresTime(account.getJsapiTicketExpiresTime());
    config.updateCardApiTicket(account.getCardApiTicket(),
        account.getCardApiTicketExpiresTime() == null ? 0
            : account.getCardApiTicketExpiresTime().intValue());
    WxMpService service = new WxMpServiceImpl();
    service.setWxMpConfigStorage(config);
    return service;
  }

}
